package dbmanager

import (
	"reflect"
	"github.com/astaxie/beego/orm"
	"fmt"
	"cloud_worm/util/umodels/mysqldb"
)

const (
	RoleGuest = 1
	RoleManager = 2
	RoleAdmin = 3
)

type WebUser struct {
	Id			int64
	Username 	string
	Password 	string
	Avatar 		string
	Role 		int
	LastLoginTime 	int64
	Updated 		int64
	Created 		int64
	Status 			int
}

func (w *WebUser) TableName() string {
	return reflect.TypeOf(*w).Name()
}

func (w *WebUser) Read(fields ...string) error {
	err := orm.NewOrm().Read(w, fields...)
	if err != nil {
		// todo: 具体错误处理，参考(https://beego.me/docs/mvc/model/object.md)
		// orm.ErrNoRows
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WebUser) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WebUser) Insert() error {
	_, err := orm.NewOrm().Insert(w)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func init() {
	orm.RegisterModel(new(WebUser))
}

func (w *WebUser) Count(status int, username string, role int, startTime int, endTime int) (int64, error) {
	qs := orm.NewOrm().QueryTable(w)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if username != mysqldb.SelectStrAll {
		qs = qs.Filter("username__istartswith", username)
	}
	if role != mysqldb.SelectIntAll {
		qs = qs.Filter("role", role)
	}

	if startTime != mysqldb.SelectIntAll {
		qs = qs.Filter("updated__gte", startTime)
	}
	if endTime != mysqldb.SelectIntAll {
		qs = qs.Filter("updated__lte", startTime)
	}

	count, err := qs.Count()
	if err != nil {
		return 0, err
	}

	return count, nil
}

/**
 选择select
 */
func (w *WebUser) Select(offset int, limit int, status int, username string, role int, startTime int, endTime int) ([]*WebUser, error) {
	var users []*WebUser

	qs := orm.NewOrm().QueryTable(w).Offset(offset).Limit(limit)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	if username != mysqldb.SelectStrAll {
		qs = qs.Filter("username__istartswith", username)
	}
	if role != mysqldb.SelectIntAll {
		qs = qs.Filter("role", role)
	}

	if startTime != mysqldb.SelectIntAll {
		qs = qs.Filter("updated__gte", startTime)
	}
	if endTime != mysqldb.SelectIntAll {
		qs = qs.Filter("updated__lte", startTime)
	}

	_, err := qs.All(&users)
	if err != nil {
		return nil, err
	}

	return users, nil
}